package com.yanqu.road.entity.activity.peakstronghold.config;

import com.yanqu.road.entity.activity.ActivityConfig;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.huashigang.HuaShiGangFloorConfig;
import com.yanqu.road.entity.activity.stronghold.config.StrongholdDonateConfig;
import com.yanqu.road.entity.config.goods.OpenGoodsBagResult;
import com.yanqu.road.entity.enums.eActivityConfigType;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.omg.CORBA.StringHolder;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PeakStrongHoldConfig {

    private ActivityInfo activityInfo;
    private ePeakStrongholdStageType stageType;
    private long nextStageTime = 0;
    private int round = 0;
    private int takeUserCount = 60;
    private int takeUnionCount = 30;

    private int topDefendPatronsNum = 2;//前两名门客防守

    private Map<Integer, HuaShiGangFloorConfig> desertConfigMap = new ConcurrentHashMap<>();
    private Map<Integer, PeakStrongholdTimeConfig> timeConfigMap = new ConcurrentHashMap<>();
    private Map<Integer, PeakStrongholdBaseConfig> baseConfigMap = new ConcurrentHashMap<>();
    private Map<Integer, PeakStrongholdDonateConfig> donateConfigMap = new ConcurrentHashMap<>();
    //按开始时间排序
    private List<PeakStrongholdTimeConfig> timeConfigList = new ArrayList<>();
    private PeakStrongholdTimeConfig registTimeConfig;//报名期配置
    private PeakStrongholdTimeConfig prepareTimeConfig;//第一个备战期配置
    //淘汰赛的轮次对应配置
    private Map<Integer, PeakStrongholdTimeConfig> roundTimeConfigMap = new ConcurrentHashMap<>();
    private List<PeakStrongholdBaseConfig> baseConfigList = new ArrayList<>();//据点星级的经验列表从0级开始

    private int unionBloodParam;
    private int rewardShovelNum;
    private String mammonHelpConsume;
    private int mammonHelpItemId;
    private int unionIntegralParam;
    private int eliminatePartonsBuyItemId;
    private String eliminatePartonsBuyItemNum;
    private int eliminateKillReward;
    private int desertPassItem;
    private List<List<Property>> desertPassRewardList = new ArrayList<>();
    private int desertShovelItemId;
    private int mammonHelpEffectType;
    private String unionBloodRankAddition;
    private List<Integer> unionBloodRankAdditionList;
    private int groupPerNum;//每组的数量
    private List<Integer> eliminateBuyNeedItemNumList;
    private int eliminatePartonsFreeTimes;
    private String worshipReward;
    private int mammonHelpItemCd;

    public ActivityInfo getActivityInfo() {
        return activityInfo;
    }

    public void setActivityInfo(ActivityInfo activityInfo) {
        this.activityInfo = activityInfo;
    }


    public void initConfig(
            Map<String, ActivityConfig> activityConfigMap,
            Map<Integer, HuaShiGangFloorConfig> tempDesertConfigMap,
            Map<Integer, PeakStrongholdTimeConfig> tempTimeConfigMap,
            Map<Integer, PeakStrongholdBaseConfig> tempBaseConfigMap,
            Map<Integer, PeakStrongholdDonateConfig> tempDonateConfigMap
    ){

        unionBloodParam = activityConfigMap.get(eActivityConfigType.union_blood_param.getName()).getIntValue();
        rewardShovelNum = activityConfigMap.get(eActivityConfigType.reward_shovel_num.getName()).getIntValue();
        mammonHelpConsume = activityConfigMap.get(eActivityConfigType.mammon_help_consume.getName()).getValue();
        for (Integer goodsId : PropertyHelper.parseStringToProperty(mammonHelpConsume).getGoods().keySet()) {
            mammonHelpItemId = goodsId;
            break;
        }
        unionIntegralParam = activityConfigMap.get(eActivityConfigType.union_integral_param.getName()).getIntValue();
        eliminatePartonsBuyItemId = activityConfigMap.get(eActivityConfigType.eliminate_partons_buy_item_id.getName()).getIntValue();
        eliminatePartonsBuyItemNum = activityConfigMap.get(eActivityConfigType.eliminate_partons_buy_item_num.getName()).getValue();
        eliminateKillReward = activityConfigMap.get(eActivityConfigType.eliminate_kill_reward.getName()).getIntValue();
        eliminatePartonsFreeTimes = activityConfigMap.get("ELIMINATE_PARTONS_FREE_TIMES").getIntValue();
        if (activityConfigMap.containsKey(eActivityConfigType.desert_pass_item.getName())) {
            desertPassItem = activityConfigMap.get(eActivityConfigType.desert_pass_item.getName()).getIntValue();
        }
        if (activityConfigMap.containsKey("HUASHIGUANG_DIG_PASS_BOX_CONTENT")) {
            this.desertPassRewardList = PropertyHelper.parseNewStringToPropertyList(activityConfigMap.get("HUASHIGUANG_DIG_PASS_BOX_CONTENT").getValue());
        }

        desertShovelItemId = activityConfigMap.get(eActivityConfigType.desert_shovel_item_id.getName()).getIntValue();
        mammonHelpEffectType = activityConfigMap.get(eActivityConfigType.mammon_help_effect_type.getName()).getIntValue();
        unionBloodRankAddition = activityConfigMap.get(eActivityConfigType.union_blood_rank_addition.getName()).getValue();
        unionBloodRankAdditionList = StringUtils.stringToIntegerList(unionBloodRankAddition, ";");
        groupPerNum = activityConfigMap.get("GROUP_PERNUM").getIntValue();
        worshipReward = activityConfigMap.get("WORSHIP_REWARD").getValue();
        if (activityConfigMap.containsKey("ITEM_TIME_INTERVAL")){
            mammonHelpItemCd = activityConfigMap.get("ITEM_TIME_INTERVAL").getIntValue();
        }

        desertConfigMap = tempDesertConfigMap;
        timeConfigMap = tempTimeConfigMap;
        baseConfigMap = tempBaseConfigMap;
        donateConfigMap = tempDonateConfigMap;

        for (PeakStrongholdTimeConfig timeConfig : timeConfigMap.values()) {
            timeConfigList.add(timeConfig);
            if (timeConfig.getType() == 1) {
                this.registTimeConfig = timeConfig;
            } else if (timeConfig.getType() == 2) {
                this.prepareTimeConfig = timeConfig;
            }
        }
        timeConfigList.sort((o1, o2) -> {
            return BigInteger.valueOf(o1.getBeginTime()).compareTo(BigInteger.valueOf(o2.getBeginTime()));
        });

        int round = 1;
        for (PeakStrongholdTimeConfig timeConfig : timeConfigList) {
            if (timeConfig.getType() == 3) {
                roundTimeConfigMap.put(round++, timeConfig);
            }
        }

        baseConfigList.addAll(baseConfigMap.values());
        baseConfigList.sort((o1, o2) -> {
            return BigInteger.valueOf(o1.getLevel()).compareTo(BigInteger.valueOf(o2.getLevel()));
        });
        int totalExp = 0;
        for (PeakStrongholdBaseConfig baseConfig : baseConfigList) {
            baseConfig.setTotalExp(totalExp);
            totalExp += Integer.valueOf(baseConfig.getNeedProcess());
        }
        baseConfigList.get(baseConfigList.size() - 1).setTotalExp(totalExp);

        eliminateBuyNeedItemNumList = StringUtils.stringToIntegerList(this.eliminatePartonsBuyItemNum, "\\|");

    }

    //淘汰赛的结束时间要小于等于endTime
    public boolean timeCheckSuccess() {
        if (timeConfigList.isEmpty()) {
            return false;
        }
        long eliminateEndTime = getEliminateEndTime();
        if (eliminateEndTime > this.activityInfo.getEndTime()) {
            return false;
        }
        return true;
    }

    public long getEliminateEndTime() {
        if (timeConfigList.isEmpty()) {
            return 0;
        }
        PeakStrongholdTimeConfig lastTimeConfig =timeConfigList.get(timeConfigList.size() - 1);
        long eliminateEndTime = (lastTimeConfig.getBeginTime()+lastTimeConfig.getDurationTime())*3600 + this.activityInfo.getBeginTime();
        return eliminateEndTime;
    }

    public String getWorshipReward(){
        return worshipReward;
    }

    public Map<Integer, PeakStrongholdTimeConfig> getTimeConfigMap() {
        return timeConfigMap;
    }

    //获取上一个多少进多少的配置
    public PeakStrongholdTimeConfig getTimeConfigForward(int timeId) {
        PeakStrongholdTimeConfig config = null;
        int minUnionCount = Integer.MAX_VALUE;
        for(PeakStrongholdTimeConfig timeConfig : timeConfigMap.values()){
            if(timeConfig.getTimeId() < timeId){
                int count = Integer.valueOf(timeConfig.getParam());
                if(count != 0 && count < minUnionCount){
                    minUnionCount = count;
                    config = timeConfig;
                }
            }
        }
        return config;
    }

    public Map<Integer, PeakStrongholdBaseConfig> getBaseConfigMap() {
        return baseConfigMap;
    }

    public Map<Integer, PeakStrongholdDonateConfig> getDonateConfigMap() {
        return donateConfigMap;
    }

    public Map<Integer, HuaShiGangFloorConfig> getDesertConfigMap() {
        return desertConfigMap;
    }


    public int getDesertPassItem() {
        return desertPassItem;
    }

    public List<List<Property>> getDesertPassRewardList() {
        return desertPassRewardList;
    }

    public ePeakStrongholdStageType getStageType() {
        long nowSecond = DateHelper.getCurrentSecond();
        if (nowSecond >= nextStageTime) {
            this.nextStageTime = calcNextCheckTime();
            this.round = calcEliminateRound();
        }
        return this.stageType;
    }

    //计算下一次阶段变化的时间
    private long calcNextCheckTime() {
        long nowSecond = DateHelper.getCurrentSecond();
        if (nowSecond >= activityInfo.getBeginShowTime() && nowSecond < activityInfo.getBeginTime()) {
            this.stageType = ePeakStrongholdStageType.BeginInShow;
            return activityInfo.getBeginTime();
        }

        if (nowSecond >= activityInfo.getEndTime() && nowSecond < activityInfo.getEndShowTime()) {
            this.stageType = ePeakStrongholdStageType.EndInShow;
            return activityInfo.getEndShowTime();
        }

        long beginHour = (nowSecond - activityInfo.getBeginTime()) / 3600;
        for (PeakStrongholdTimeConfig timeConfig : timeConfigList) {
            if (beginHour >= timeConfig.getBeginTime() && beginHour < (timeConfig.getEndTime())) {
                if (timeConfig.getType() == 1) {
                    this.stageType = ePeakStrongholdStageType.Registration;
                } else if (timeConfig.getType() == 3) {
                    this.stageType = ePeakStrongholdStageType.InBattle;
                } else {
                    this.stageType = ePeakStrongholdStageType.Prepare;
                }
                return activityInfo.getBeginTime() + timeConfig.getEndTime() * 3600;
            }
            if (beginHour < timeConfig.getBeginTime()) {
                this.stageType = ePeakStrongholdStageType.Prepare;
                return activityInfo.getBeginTime() + timeConfig.getBeginTime() * 3600;
            }
        }
        if (nowSecond < activityInfo.getEndTime()) {//最后一回合的结束时间
            this.stageType = ePeakStrongholdStageType.InBattle;
            return activityInfo.getEndTime();
        }

        this.stageType = ePeakStrongholdStageType.EndInShow;
        return activityInfo.getEndShowTime();
    }

    public long getNextStageTime() {
        return nextStageTime;
    }

    public int getRound() {
        getStageType();
        return round;
    }

    //根据时间获得淘汰赛回合数
    public int calcEliminateRound() {
        long nowSecond = DateHelper.getCurrentSecond();
        long beginHour = (nowSecond - activityInfo.getBeginTime()) / 3600;
        if (beginHour < prepareTimeConfig.getBeginTime()) {
            return 0;
        }
        int round = 1;
        for (int i =0;i<timeConfigList.size() - 1;i++){
            PeakStrongholdTimeConfig timeConfig = timeConfigList.get(i);
            if (timeConfig.getType() == 3 && beginHour >= timeConfig.getEndTime()) {
                //淘汰赛持续时间结束回合加1
                round++;
            }
            if (beginHour < timeConfig.getBeginTime()) {
                break;
            }
        }

        return round;
    }

    //获取timeconfig
    public PeakStrongholdTimeConfig getTimeConfig(int stageType, int round) {
        if (stageType == ePeakStrongholdStageType.Registration.getValue()) {
            return registTimeConfig;
        } else if (stageType == ePeakStrongholdStageType.Prepare.getValue()) {
            return prepareTimeConfig;
        } else {
            return roundTimeConfigMap.get(round);
        }
    }

    public PeakStrongholdTimeConfig getTimeConfig(int timeId){
        return timeConfigMap.get(timeId);
    }

    //获取对应阶段的结束时间
    public long getRoundEndTime(int round){
        PeakStrongholdTimeConfig timeConfig = roundTimeConfigMap.get(round);
        long time = activityInfo.getBeginTime() + timeConfig.getBeginTime() * 60 * 60 + timeConfig.getDurationTime() * 60 * 60;
        //最后一轮的时间，结束时间会被修正成活动结束时间
        if(round == getTotalRound()){
            if(time < activityInfo.getEndTime()){
                time = activityInfo.getEndTime();
            }
        }
        return time * 1000;
    }

    public long getTimeConfigEndTime(int timeId){
        PeakStrongholdTimeConfig timeConfig = timeConfigMap.get(timeId);
        long time = activityInfo.getBeginTime() + timeConfig.getBeginTime() * 60 * 60 + timeConfig.getDurationTime() * 60 * 60;
        //最后一轮的时间，结束时间会被修正成活动结束时间
        PeakStrongholdTimeConfig finalTimeConfig = roundTimeConfigMap.get(getTotalRound());
        if(timeId == finalTimeConfig.getTimeId()){
            if(time < activityInfo.getEndTime()){
                time = activityInfo.getEndTime();
            }
        }
        return time * 1000;
    }

    public long getTimeConfigBeginTime(int timeId){
        PeakStrongholdTimeConfig timeConfig = timeConfigMap.get(timeId);
        long time = activityInfo.getBeginTime() + timeConfig.getBeginTime() * 60 * 60;
        return time * 1000;
    }

    public int getGroupPerNum() {
        return groupPerNum;
    }

    public int getTopDefendPatronsNum() {
        return topDefendPatronsNum;
    }

    //获得据点等级对应的血量加成
    public int getUnionBaseAdd(int lv) {
        PeakStrongholdBaseConfig config = baseConfigMap.get(lv);
        if (config != null) {
            return config.getHpAdd();
        }
        return 0;
    }

    //获得据点等级对应的血量加成
    public int getUnionBaseAddByExp(int totalExp) {
        PeakStrongholdBaseConfig config = getBaseConfigByExp(totalExp);
        if (config != null) {
            return config.getHpAdd();
        }
        return 0;
    }

    //获取排行对应的血量加成
    public int getHpAddByRank(int rank) {
        if (rank <= 0) {
            return 0;
        }
        if (rank > this.unionBloodRankAdditionList.size()) {
            return 0;
        }
        return this.unionBloodRankAdditionList.get(rank - 1);
    }

    //根据经验获得配置
    public PeakStrongholdBaseConfig getBaseConfigByExp(int totalExp) {
        PeakStrongholdBaseConfig resultConfig = null;
        for (PeakStrongholdBaseConfig baseConfig : baseConfigList) {
            if (totalExp >= baseConfig.getTotalExp()) {
                resultConfig = baseConfig;
            } else {
                break;
            }
        }

        return resultConfig;
    }

    //门客赚力对应血量
    public BigInteger caluPatronsBlood(BigInteger ability) {
        int enlargeValue = this.unionBloodParam;
        return new BigDecimal(ability).multiply(new BigDecimal(enlargeValue)).divide(new BigDecimal(1000), BigDecimal.ROUND_UP).toBigInteger();
    }

    //淘汰赛总回合数
    public int getTotalRound() {
        return roundTimeConfigMap.size();
    }

    //免费出战次数
    public int getEliminateFreeTimes() {
        return this.eliminatePartonsFreeTimes;
    }

    //恢复出战次数上限
    public int getEliminateBuyTimes() {
        return this.eliminateBuyNeedItemNumList.size();
    }

    //出战道具消耗
    public Property getEliminateConsume(int buyTimes) {
        if (buyTimes < 0 || buyTimes >= this.eliminateBuyNeedItemNumList.size()) {
            return null;
        }
        int countNeed = this.eliminateBuyNeedItemNumList.get(buyTimes);
        int itemId = this.eliminatePartonsBuyItemId;

        return new Property(itemId, BigInteger.valueOf(countNeed));
    }

    //复活使用多少复活道具,已经是复活完了
    public int getEliminateItemNum(int buyTimes){
        if (buyTimes == 0 || buyTimes > this.eliminateBuyNeedItemNumList.size()) {
            return 0;
        }
        //复活完了
        int countNeed = this.eliminateBuyNeedItemNumList.get(buyTimes - 1);
        return countNeed;
    }

    //根据伤害计算积分
    public BigInteger calcDamageToScore(BigInteger damage, BigInteger curBlood, BigInteger totalBlood) {

        BigDecimal petcent = new BigDecimal(curBlood).divide(new BigDecimal(totalBlood), 10, RoundingMode.HALF_UP);
        BigDecimal param1 = petcent.multiply(new BigDecimal(this.unionIntegralParam)).divide(new BigDecimal("1000"), 10, RoundingMode.HALF_UP);
        BigDecimal curScore = new BigDecimal(damage).multiply(BigDecimal.ONE.add(param1)).setScale(0, BigDecimal.ROUND_UP);
        return curScore.toBigInteger();
    }

    public int getKillItemId(){
        int killItemId = this.eliminateKillReward;
        return killItemId;
    }

    /**
     * 淘汰赛每次出战获得的奖励
     *
     * @param buyTimes
     * @return
     */
    public Property getEliminateChallengeReward(int buyTimes) {
        int shovelItemId = this.desertShovelItemId;
        int shovelNum = 1 + this.rewardShovelNum * getEliminateItemNum(buyTimes);
        return new Property(shovelItemId, BigInteger.valueOf(shovelNum));
    }
    //挖宝道具
    public int getDesertShovelItemId(){
        return desertShovelItemId;
    }

    public String getMammonHelpConsume() {
        return mammonHelpConsume;
    }

    //财神助力消耗道具
    public Integer getMammonHelpItemId() {
        return mammonHelpItemId;
    }

    public int getMammonHelpEffectType() {
        return mammonHelpEffectType;
    }

    public int getTakeUserCount() {
        return takeUserCount;
    }

    public int getTakeUnionCount() {
        return takeUnionCount;
    }

    public PeakStrongholdTimeConfig getCurBattleTimeConfig() {
        long nowSecond = DateHelper.getCurrentSecond();
        long beginHour = (nowSecond - activityInfo.getBeginTime()) / 3600;
        for (PeakStrongholdTimeConfig timeConfig : timeConfigList) {
            if (beginHour >= timeConfig.getBeginTime() && beginHour < (timeConfig.getEndTime())) {
                return timeConfig;
            }
        }
        return null;
    }

    public int getMammonHelpItemCd() {
        return mammonHelpItemCd;
    }

    public int getRoundByTimeId(int timeId) {
        for (Map.Entry<Integer, PeakStrongholdTimeConfig> entry : roundTimeConfigMap.entrySet()) {
            Integer round = entry.getKey();
            PeakStrongholdTimeConfig timeConfig = entry.getValue();
            if (timeConfig.getTimeId() == timeId) {
                return round;
            }
        }
        return 0;
    }
}
